import { computed, unref, reactive } from 'vue'

export enum LabelDirection {
  Left = 'left',
  Right = 'right',
  Top = 'top'
}

export enum FormLayout {
  Vertical,
  Horizontal
}

export interface Options {
  labelDirection: LabelDirection
  layout: FormLayout
  colNum: number | 'auto'
  labelWidth: number
  wrapperWidth: number | '100%'
}

const defaultOptions: Options = {
  labelDirection: LabelDirection.Right,
  layout: FormLayout.Horizontal,
  colNum: 'auto',
  labelWidth: 120,
  wrapperWidth: '100%'
}

export function useFormLayout(options: Partial<Options> = {}) {
  const { labelDirection, layout, colNum, labelWidth, wrapperWidth } = {
    ...defaultOptions,
    ...options
  }

  const formLayout = computed(() => {
    if (labelDirection === LabelDirection.Top) {
      return 'vertical'
    }
    return 'horizontal'
  })
  const colSpan = computed(() => {
    if (layout === FormLayout.Vertical) {
      return 24
    }
    if (colNum === 'auto') {
      return colNum
    }
    return layout === FormLayout.Horizontal ? 24 / colNum : 24
  })
  const labelAlign = computed(() =>
    labelDirection === LabelDirection.Top ? 'left' : labelDirection
  )

  const formBindLayout = reactive({
    labelCol: { style: { width: labelWidth + 'px' } },
    wrapperCol: {
      style: {
        width: wrapperWidth === '100%' ? wrapperWidth : wrapperWidth + 'px'
      }
    },
    layout: unref(formLayout),
    labelAlign: unref(labelAlign)
  })
  return {
    formBindLayout,
    colSpan
  }
}